import { Context } from 'koa'
import { userService } from '../services/user'

export class UserController {
  // 用户注册
  async register(ctx: Context) {
    const userData = ctx.request.body
    const user = await userService.createUser(userData)
    ctx.status = 201
    ctx.body = {
      success: true,
      data: user,
      message: '用户注册成功'
    }
  }

  // 用户登录
  async login(ctx: Context) {
    const { username, password } = ctx.request.body
    const result = await userService.login(username, password)
    ctx.status = 200
    ctx.body = result
  }

  // 用户退出登录
  async logout(ctx: Context) {
    const authHeader = ctx.request.header?.authorization
    if (authHeader) {
      const tokenParts = authHeader.split(' ')
      if (tokenParts.length === 2 && tokenParts[0] === 'Bearer') {
        const token = tokenParts[1]
        // 将token加入黑名单
        const { addToBlacklist } = await import('../utils/jwtToken')
        addToBlacklist(token)
      }
    }
    
    ctx.status = 200
    ctx.body = {
      success: true,
      message: '用户退出登录成功'
    }
  }

  // 获取用户列表
  async findAll(ctx: Context) {
    const users = await userService.findAll(ctx.query)
    ctx.status = 200
    ctx.body = {
      success: true,
      data: users,
      message: '获取用户列表成功'
    }
  }

  // 获取单个用户
  async findOne(ctx: Context) {
    const { id } = ctx.params
    const user = await userService.getUserById(id)
    ctx.status = 200
    ctx.body = {
      success: true,
      data: user,
      message: '获取用户成功'
    }
  }

  // 更新用户信息
  async update(ctx: Context) {
    const { id } = ctx.params
    const updateData = ctx.request.body
    const user = await userService.updateUser(id, updateData)
    ctx.status = 200
    ctx.body = {
      success: true,
      data: user,
      message: '用户信息更新成功'
    }
  }

  // 删除用户
  async delete(ctx: Context) {
    const { id } = ctx.params
    await userService.deleteUser(id)
    ctx.status = 200
    ctx.body = {
      success: true,
      message: '用户删除成功'
    }
  }

  // 检查用户名是否存在
  async isUsernameExist(ctx: Context) {
    const { username } = ctx.params
    const exists = await userService.checkUsernameExists(username)
    ctx.status = 200
    ctx.body = {
      success: true,
      data: { exists },
      message: '查询成功'
    }
  }

  // 重置用户密码
  async resetPassword(ctx: Context) {
    const { id } = ctx.params
    const { newPassword } = ctx.request.body
    const result = await userService.resetPassword(id, newPassword)
    ctx.status = 200
    ctx.body = result
  }
}

export const userController = new UserController()
